package main

import "time"

func main() {

	doWork := func(
		done <-chan interface{},
		pulseInterval time.Duration,
	) (<-chan interface{}, <-chan time.Time) {
		heartbeat := make(chan interface{}) //创建发送心跳的channel，返回给doWork
		results := make(chan time.Time)
		go func() {
			defer close(heartbeat)
			defer close(results)

			pulse := time.Tick(pulseInterval)       //设置心跳的间隔时间，pulseInterval，期间会读取channel
			workGen := time.Tick(2 * pulseInterval) //时间大于pluseInterval，方便聪goroutine中看倒心跳

			sendPulse := func() {
				select {
				case heartbeat <- struct{}{}:
				default: //默认语句，可能没有接收心跳
				}
			}
			sendResult := func(r time.Time) {
				for {
					select {
					case <-done:
						return
					case <-pulse: //同done channel，执行接收或发送时，需要一个发送心跳的分支
						sendPulse()
					case results <- r:
						return
					}
				}
			}

			for {
				select {
				case <-done:
					return
				case <-pulse:
					sendPulse()
				case r := <-workGen:
					sendResult(r)
				}
			}
		}()
		return heartbeat, results
	}
}